package com.seeyon.apps.leaveRecord.event;

import cn.hutool.core.convert.Convert;
import com.seeyon.apps.attendance.manager.AttendanceSettingManager;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.*;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ModuleType;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.content.mainbody.MainbodyManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.po.content.CtpContentAll;
import com.seeyon.ctp.login.UserUtil;
import com.seeyon.ctp.util.JDBCAgent;
import com.seeyon.ctp.workflow.event.AbstractWorkflowEvent;
import com.seeyon.ctp.workflow.event.WorkflowEventData;
import com.seeyon.ctp.workflow.event.WorkflowEventResult;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import static com.seeyon.apps.attendance.utils.AttendanceUtil.isWorkDay;
import static com.seeyon.apps.leaveRecord.util.CAP4FormKit.*;
import static com.seeyon.apps.leaveRecord.util.EnumUtils.getEnumItemName;
import static com.seeyon.apps.quartz.util.CAP4FormKit.getFieldTaleId;
import static com.seeyon.apps.quartz.util.CAP4FormKit.getSubBeans;

/**
 * @Author: SPK
 * @Date: 2022/6/21 16:24
 * @Description:
 */
public class LeaveWriteEvent extends AbstractWorkflowEvent {
    protected FormApi4Cap4 formApi4Cap4;
    protected static final Log log = LogFactory.getLog(LeaveWriteEvent.class);
    private MainbodyManager ctpMainbodyManager;
    private AttendanceSettingManager attendanceSettingManager;


    public void setAttendanceSettingManager(AttendanceSettingManager attendanceSettingManager) {
        this.attendanceSettingManager = attendanceSettingManager;
    }

    @Override
    public String getId() {
        return "leaveWriteEvent";
    }

    @Override
    public String getLabel() {
        return "请假单回写事件";
    }

    @Override
    public ApplicationCategoryEnum getAppName() {
        return ApplicationCategoryEnum.form;
    }

    @Override
    public WorkflowEventResult onBeforeFinishWorkitem(WorkflowEventData data) {
        WorkflowEventResult result = new WorkflowEventResult();
        try {
            User user = UserUtil.build("seeyonx", "", null);
            if (user != null) {
                UserUtil.setCurrentUser(user);
            }
            Long accountId = user.getAccountId();
            Map<String, Object> map = data.getBusinessData();
            //获取假勤档案管理表
            FormBean CheckFromDing = getFormApi4Cap4().getFormByFormCode("CheckFromDing");
            // 获取流程事件表单
            FormDataMasterBean master = (FormDataMasterBean) map.get("formDataBean");
            List<FormDataSubBean> subBeans = getSubBeans(master, "请假明细");
            //获取对应档案
            AtomicInteger num = new AtomicInteger();
            subBeans.forEach(element -> {
                String typeEnum = getSubFieldStrValue(element, "请假类型");
                String type = getEnumItemName(typeEnum);
                String days = getFieldStrValue(element, "请假天数");

                if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(days)) {

                    Date startTime = (Date) getSubFieldValue(element, "请假开始时间");
                    String startNoonEnum = getSubFieldStrValue(element, "请假开始时间-上下午");

                    String startNoon = getEnumItemName(startNoonEnum);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startTime);
                    Double douDays = Double.valueOf(days);
                    if (douDays >= 0.5) {
                        douDays = douDays * 2;
                        Boolean isPlu = false;
                        for (int i = 0; i < douDays; i++) {
                            if (0 == i && startNoon.equals("下午")) {
                                isPlu = true;
                            } else if (isPlu) {
                                if (0 != i % 2) {
                                    calendar.add(Calendar.DATE, 1);
                                }
                            } else if (0 == i % 2 && 0 != i) {
                                calendar.add(Calendar.DATE, 1);
                            }
                            Date date = calendar.getTime();
                            try {
                                while (!isWorkDay(date, accountId, attendanceSettingManager.getCurrentAttendanceSettingByAccountId(accountId))) {
                                    calendar.add(Calendar.DATE, 1);
                                    date = calendar.getTime();
                                }
                            } catch (BusinessException e) {
                                log.info("查询是否工作日失败", e);
                            }
                            date = calendar.getTime();
                            String tableName = CheckFromDing.getMasterTableBean().getTableName();
                            String attDate = getFieldTaleId(CheckFromDing, "考勤日期");
                            String name = getFieldTaleId(CheckFromDing, "姓名");
                            String userId = getFieldStrValue(master, "申请人");

                            List<Map<String, Object>> count = null;
                            ArrayList<Object> param = new ArrayList<>();
                            param.add(date);
                            param.add(userId);
                            try (JDBCAgent agent = new JDBCAgent(true, false)) {
                                //
                                agent.execute("select id from " + tableName + " where " + attDate + " = ? " + "and " + name + " = ?", param);
                                count = agent.resultSetToList();
                            } catch (Exception e) {
                                log.error("查询主表出错", e);
                            }
                            AtomicReference<FormDataMasterBean> atoMasterBean = new AtomicReference();
                            if (count.size() > 0) {
                                count.forEach(row -> {
                                    try {
                                        atoMasterBean.set(getFormApi4Cap4().findDataById(Convert.toLong(row.get("id")), CheckFromDing.getId(), null));
                                    } catch (Exception e) {
                                        log.error("根据id查询表单出错", e);
                                    }
                                });
                            } else {
                                log.info("该人员没有对应的钉钉假勤档案");
                            }
                            FormDataMasterBean masterBean = atoMasterBean.get();
                            if (null != masterBean) {
                                if (i == 0) {
                                    setCellValue(masterBean, startNoon.equals("上午") ? "上午-是否有请假" : "下午-是否有请假", "是");

                                } else if ("上午".equals(startNoon)) {
                                    setCellValue(masterBean, 0 == i % 2 ? "上午-是否有请假" : "下午-是否有请假", "是");

                                } else {
                                    setCellValue(masterBean, 0 == i % 2 ? "下午-是否有请假" : "上午-是否有请假", "是");

                                }
                                try {
                                    getFormApi4Cap4().saveOrUpdateFormData(masterBean, CheckFromDing.getId(), true);
                                } catch (Exception e) {
                                    log.error("保存正文数据异常：", e);
                                }
                            }else {
                                result.setAlertMessage("请假单回写钉钉考勤档案事件失败,没有对应的钉钉考勤档案");
                            }

                        }
                    }
                }
            });
        } catch (Exception e) {
            log.error("请假单回写事件失败", e);
            result.setAlertMessage("请假单回写事件失败");
        }

        return result;
    }

    public FormApi4Cap4 getFormApi4Cap4() {
        if (null == formApi4Cap4) {
            formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
        }
        return formApi4Cap4;
    }

    private MainbodyManager getCtpMainbodyManager() {
        if (null == ctpMainbodyManager) {
            ctpMainbodyManager = (MainbodyManager) AppContext.getBean("ctpMainbodyManager");
        }
        return ctpMainbodyManager;
    }
}
